using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using SharePointHNSC.Timerjob;

namespace SharePointHNSC.Features.HNSC
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("30470fd8-ff3f-403b-a114-a09fdfd843e7")]
    public class HNSCEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {


            SPService adminService = SPFarm.Local.Services.Where(s => s.DisplayName.Equals("WSS_Administration")).FirstOrDefault();
            
            try
            {
                this.DeleteTimerJob(adminService, ApplyApplicationContentToAllServerTimerJob.TIMERJOB_NAME);

                ApplyApplicationContentToAllServerTimerJob applyApplicationContentToAllServerJob = new ApplyApplicationContentToAllServerTimerJob(ApplyApplicationContentToAllServerTimerJob.TIMERJOB_NAME, adminService);
                applyApplicationContentToAllServerJob.Update();

                this.RunTimerJob(adminService, ApplyApplicationContentToAllServerTimerJob.TIMERJOB_NAME);
            }
            catch (Exception ex)
            {
                SPDiagnosticsCategory diagnosticsCategory = new SPDiagnosticsCategory("HNSC", TraceSeverity.Unexpected, EventSeverity.Error);
                SPDiagnosticsService.Local.WriteTrace(0, diagnosticsCategory, TraceSeverity.Unexpected, ex.Message, ex);
                throw (ex);
            }
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPService adminService = SPFarm.Local.Services.Where(s => s.DisplayName.Equals("WSS_Administration")).FirstOrDefault();

            try
            {
                DeleteTimerJob(adminService, ApplyApplicationContentToAllServerTimerJob.TIMERJOB_NAME);
            }
            catch (Exception ex)
            {
                SPDiagnosticsCategory diagnosticsCategory = new SPDiagnosticsCategory("HNSC", TraceSeverity.Unexpected, EventSeverity.Error);
                SPDiagnosticsService.Local.WriteTrace(0, diagnosticsCategory, TraceSeverity.Unexpected, ex.Message, ex);
                throw (ex);
            }
        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}

        private void DeleteTimerJob(SPService service, string name)
        {
            var timerjob = this.GetTimerJob(service, name);

            if (timerjob != null)
            {
                timerjob.Delete();
            }
        }

        private void RunTimerJob(SPService service, string name)
        {
            var timerjob = this.GetTimerJob(service, name);

            if (timerjob != null)
            {
                timerjob.RunNow();
            }
        }

        private SPJobDefinition GetTimerJob(SPService service, string name)
        {
            return (from jobDefinition in service.JobDefinitions
                where jobDefinition.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)
                select jobDefinition).SingleOrDefault();
        }
    }
}
